const mongoose = require('mongoose');
const News=require('../models/news.model');
//新增
exports.create=function(req,res,next){
    console.log(req.body)
    const news = new News(req.body);
    news.save().then((data) =>{
        res.json(data);
    });
}

// 修改
exports.update=function(req,res,next){
    const id=req.params.id;
    News.findByIdAndUpdate(id,{$set:req.body},{new:false}).then(data=>{
        res.json(data); //返回的是修改之前的数据
    });
}
// 删除单个
exports.remove=function(req,res,next){
    const id=req.params.id;//获取到前端的id
    News.findByIdAndDelete(id,(err,data)=>{//更具id删除数据
        res.json(data);
    });
}

// 删除多个
// exports.removes=function(req,res,next){
//     var ids=req.body.ids.split(',');
//     if(ids.length>0){
//         News.remove({_id:{$in:ids}}).then(data=>{
//             res.json('message:ok'+'status:200');
//         })
//     }
//     // News.findByIdAndDelete(id,(err,data)=>{
//     //     res.json(data);
//     // });
// }
exports.removes = function(req, res, next) {
    console.log(req.body.ids)
    var ids = req.body.ids.split(',');
    News.remove({ _id: { $in: ids } }).then(data => {
      res.json({ message: '数据删除成功', status: 200 });
    });
  };

// 查询
exports.list=function(req,res,next){
    var page=req.body.page ? req.body.page : 1;
    var rows=req.body.rows ? req.body.rows : 5;
    
    var queryCondition={};
    if(req.body.dimtitle){
        //根据查询条件搜索记录
        all=req.body.dimtitle;
        var str='(.*)'+all+'(.*)';
        queryCondition={
            $or:[
             {"title":new RegExp(str,'g')},
             {"name":new RegExp(str,'g')},
            {"content":new RegExp(str,'g')}
            ]
        }
    }else if(req.body.dimcate && req.body.dimcate.trim().length>0){
        //显示分类数据
        cate=req.body.dimcate.split(',').join('|');
        var reg=new RegExp(cate,'g');
        queryCondition={
            "cate":reg
        }
    }else{
        //显示全部数据
        title=req.body.title;
        queryCondition={
            "title":new RegExp(title,'i')
        }
    }
    News.paginate(queryCondition, { page: +page, limit:+rows }, function(err, result) {
        result.rows=result.docs;
        delete result.docs;
        res.json(result);
    });
}

//查询单条记录
exports.getData=function(req,res,next){
    const id=req.params.id;
    News.findById(id).then(data=>{
        res.json(data);
    })
}